#include "head.h"
#include "operate.h"

// 子线程的入口函数
void * threadMain(void *p){
    status_t *status = (status_t *)p;
    //和数据库建立连接
    //pthread_mutex_lock(&status->lockD);
    //MYSQL* mysql;
    //mysql = mysql_init(NULL);
    //connMySQL(mysql);
    //pthread_mutex_unlock(&status->lockD);
    // 循环去队列中取net_fd, 和客户端通信
    while(1){

        // 取net_fd: 队列
        pthread_mutex_lock(&status->lock);
        // 判断队列中是否有内容
        while(status->queue.size == 0  && status->exitFlag == 0){
            // 队列中没有新的客户端链接, 等待
            pthread_cond_wait(&status->cond, &status->lock);
        }

        if(status->exitFlag == 1){
            // 要退出
            // TODO: 释放资源
            pthread_mutex_unlock(&status->lock);
            pthread_exit(NULL);
        }

        int net_fd = status->queue.head->net_fd; 

        deQueue(&status->queue); 
        pthread_mutex_unlock(&status->lock);

        Client cli;
        memset(&cli, 0, sizeof(cli));

        while(1){
            /*拿到一个新的客户端链接: net_fd*/
            int ret =recv(net_fd, &cli, sizeof(cli), MSG_WAITALL);
            if(ret == -1){
                /*数据接收失败，通知客户端重新发送*/
                //todo...
            }else if(ret == 0){
                /*客户端断开连接*/
                printf("用户：%s断开了连接\n", cli.user.name);
                break;
            }
            
            ret = access("./user", F_OK);
            char user_path[OP_NAME_SIZE] = {0};
            sprintf(user_path, "./user/%s", cli.user.name);
            if(ret == -1){
                //logInfo
                mkdir("./user", 0775);
                mkdir(user_path, 0775);
            }
            
            ret = access(user_path, F_OK);
            if(ret == -1){
                //logInfo
                mkdir(user_path, 0775);
            }
            
            //ret = chdir(user_path);
            if(ret == -1){
                //todo
            }

            /*处理客户端发来的命令*/
            cli.user.fd_net = net_fd;
            handleCli(&cli);


        }// !while, 用户断开连接
    }// !while, 收到结束线程的信号

    //mysql_close(mysql);
    return NULL;
}
